package com.koocloud.electroplatemanage.service.impl;

import cn.hutool.core.lang.Validator;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.koocloud.electroplatemanage.common.pojo.ResponseTemplate;
import com.koocloud.electroplatemanage.mapper.AnalysisItemsMapper;
import com.koocloud.electroplatemanage.mapper.OriginItemsMapper;
import com.koocloud.electroplatemanage.mapper.TankMapper;
import com.koocloud.electroplatemanage.pojo.AnalysisItems;
import com.koocloud.electroplatemanage.pojo.OriginItems;
import com.koocloud.electroplatemanage.pojo.Tank;
import com.koocloud.electroplatemanage.pojo.TypeWorkVo;
import com.koocloud.electroplatemanage.service.TankService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import static com.koocloud.electroplatemanage.constant.IncomePartJudgeSqlFieldConstant.*;
import static com.koocloud.electroplatemanage.constant.IncomePartJudgeSqlFieldConstant.ZERO;

/**
 * @program:
 * @description: 镀槽服务层实现类
 * @author: wjx
 * @create: 2020/11/12 17:56
 */
@Service
@Transactional(rollbackFor=Exception.class)
public class TankServiceImpl implements TankService {

    @Resource
    TankMapper tankMapper;

    @Resource
    OriginItemsMapper originItemsMapper;

    @Resource
    AnalysisItemsMapper analysisItemsMapper;
    Lock lock = new ReentrantLock();
    /**
     * 通过主键ID搜索镀槽
     * @param pk
     * @return
     */
    @Override
    public ResponseTemplate selectByPk(String pk) {
        try {
            //新建工种实体
            Tank tank = null;
            tank = tankMapper.selectByPk(pk);
            //判断查表操作是否成功
            if (null != tank) {
                List<OriginItems> list = originItemsMapper.selectByTankNo(tank.getTankNo());
                if (!list.isEmpty()){
                    tank.setOriginItemsList(list);
                    //查表成功返回数据
                    return ResponseTemplate.builder().code(0).message("查询成功").count(1l).data(tank).build();
                }else {
                    //查表成功返回数据
                    return ResponseTemplate.builder().code(0).message("该镀槽没有化验项目").count(1l).data(tank).build();
                }
            }
            else {
                //查表失败返回提示
                return ResponseTemplate.builder().code(1).message("没有此数据").count(0l).build();
            }
        } catch (Exception e) {
            //遇到异常，返回异常原因
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResponseTemplate.builder().code(1).message(e.getMessage()).count(0l).build();
        }
    }

    /**
     *@Description:查询所有记录 分页
     *@Param: [page, limit]
     *@return: com.koocloud.electroplatemanage.common.ResponseTemplate
     *@Author: wjx
     *@date: 2020/11/16
     */
    @Override
    public ResponseTemplate selectAllData(String page, String limit, Tank tank) {
        //校验分页参数是否为纯数字 并且page和limit不都等于0
        if(Validator.isNumber(page)&&Validator.isNumber(limit)&&!("0".equals(page)&&"0".equals(limit))) {
            try {
                //开始分页
                PageHelper.startPage(Integer.valueOf(page), Integer.valueOf(limit));
                List<Tank> TankList = new ArrayList<>();
                //判断模糊查询是否为状态查询 启用为 1 禁用为 0
                if (!StringUtils.isEmpty(tank.getIdOrName())){
                    //启用
                    if (STARTUSING.equals(tank.getIdOrName())){
                        tank.setIdOrName(ONE);
                        TankList = tankMapper.selectByDeleteFlag(tank);
                        //禁用
                    } else if (FORBIDDEN.equals(tank.getIdOrName())){
                        tank.setIdOrName(ZERO);
                        TankList = tankMapper.selectByDeleteFlag(tank);
                        //模糊查询
                    }else {
                        TankList = tankMapper.selectAllData(tank);
                    }
                }else {
                    //全局查询
                    TankList = tankMapper.selectAllData(tank);
                }
                //构造分页实体
                PageInfo<Tank> info=new PageInfo<>(TankList);
                if (info.getTotal()>0) {
                    //查询到数据
                    return ResponseTemplate.builder().code(0).message("查询成功").count(info.getTotal()).data(info.getList()).build();
                } else {
                    //没有查询到数据
                    return ResponseTemplate.builder().code(1).message("没有查到对应数据").count(0l).build();
                }
            } catch (Exception e) {
                //遇到异常，返回异常原因
                e.printStackTrace();
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return ResponseTemplate.builder().code(1).message(e.getMessage()).count(0l).build();
            }
        }
        else {
            return ResponseTemplate.builder().code(1).message("分页参数错误").count(0l).build();
        }
    }

    @Override
    public ResponseTemplate rSelectAllData(Tank tank) {
        try{
            List<Tank> TankList = new ArrayList<>();
            //全局查询
            TankList = tankMapper.selectAllData(tank);
            if (TankList.size()>0) {
                //查询到数据
                return ResponseTemplate.builder().code(0).message("查询成功").count((long)TankList.size()).data(TankList).build();
            } else {
                //没有查询到数据
                return ResponseTemplate.builder().code(1).message("没有查到对应数据").count(0l).build();
            }
        } catch (Exception e) {
            //遇到异常，返回异常原因
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResponseTemplate.builder().code(1).message(e.getMessage()).count(0l).build();
        }
    }

    /**
     *@Description: 校验填写的镀槽表编号
     *@Param: [tank]
     *@return: com.koocloud.electroplatemanage.common.pojo.ResponseTemplate
     *@Author: wjx
     *@date: 2020/11/16
     */
    @Override
    public ResponseTemplate check(Tank tank) {
        try{
            log("传入的镀槽编号为："+tank.getTankNo());
            if (!StringUtils.isEmpty(tank.getTankNo())){//判断传入的镀槽编号为空
                //根据镀槽编号查询一条数据
                Tank tank1 = tankMapper.selectByTankNo(tank.getTankNo());
            if(!StringUtils.isEmpty(tank1)){
                return ResponseTemplate.builder().code(1).message("填写的镀槽表镀槽编号已存在,请重新输入").count(1l).build();
            }else {
                return ResponseTemplate.builder().code(0).message("此镀槽表镀槽编号可用").count(1l).build();
            }
            }else{
                return ResponseTemplate.builder().code(1).message("传入的镀槽编号为空").count(1l).build();
            }
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResponseTemplate.builder().code(1).message(e.toString()).count(0l).build();
        }
    }

    /**
     *@Description://插入一条记录
     *@Param: [tank]
     *@return: com.koocloud.electroplatemanage.common.ResponseTemplate
     *@Author: wjx
     *@date: 2020/11/16
     */
    @Override
    public ResponseTemplate insert(Tank tank) {
       try{
           lock.lock();
           //查询镀槽是否存在
           Tank tankByName = tankMapper.selectByName(tank.getTankName());
           Tank tank1 = tankMapper.selectByTankNo(tank.getTankNo());
           if(!StringUtils.isEmpty(tankByName)||!StringUtils.isEmpty(tank1)){
               return ResponseTemplate.builder().code(1).message("该镀槽已存在，或重名！").count(0l).build();
           }else {
               //存入工种表
               int rows = tankMapper.insert(tank);
               List<OriginItems> originItemsList = tank.getOriginItemsList();
               String tankNo = tank.getTankNo();
                if(!StringUtils.isEmpty(originItemsList)){
                    for (OriginItems originItems : originItemsList) {
                        originItems.setTankNo(tankNo);
                    }
                    originItemsMapper.batchInsert(tankNo,originItemsList);
                }
               if(rows > 0){
                   return ResponseTemplate.builder().code(0).message("插入数据成功").count(1l).build();
               } else {//没有异常并且插入数据失败，原则上不出现
                   return ResponseTemplate.builder().code(1).message("插入数据失败").count(0l).build();
               }
           }

       }catch (Exception e) {
           e.printStackTrace();
           TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
           return ResponseTemplate.builder().code(1).message(e.toString()).count(0l).build();
       }finally {
           lock.unlock();
       }
    }

    /**
     *@Description:批量插入记录
     *@Param: [tank]
     *@return: com.koocloud.electroplatemanage.common.ResponseTemplate
     *@Author: wjx
     *@date: 2020/11/16
     */
    @Override
    public ResponseTemplate batchInsert(List<Tank> listTank) {
        if(!listTank.isEmpty()) {
            try {
                lock.lock();
                //没有异常并且插入数据条数大于0
                int rows = tankMapper.batchInsert(listTank);
                if (rows > 0) {
                    return ResponseTemplate.builder().code(0).message("批量插入数据成功").count((long)rows).build();
                } else {//没有异常并且插入数据失败，原则上不出现
                    return ResponseTemplate.builder().code(1).message("批量插入数据失败").count(0l).build();
                }
            } catch (Exception e) {
                //出现异常返回异常原因
                e.printStackTrace();
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return ResponseTemplate.builder().code(1).message(e.getMessage()).count(0l).build();
            }finally {
                lock.unlock();
            }
        }
        else {
            return ResponseTemplate.builder().code(1).message("传入参数为空").count(0l).build();
        }
    }

    /**
     *@Description:逻辑删除一条记录
     *@Param: [pk]
     *@return: com.koocloud.electroplatemanage.common.ResponseTemplate
     *@Author: wjx
     *@date: 2020/11/16
     */
    @Override
    public ResponseTemplate delete(String pk, String deleteFlag) {
        try {
            lock.lock();
            int rows = tankMapper.delete(pk,deleteFlag);
            //判断删除操作是否成功
            if (rows > 0) {
                //删除成功返回数据
                return ResponseTemplate.builder().code(0).message("删除成功").count(1l).build();
            }
            else {
                //删除失败返回提示
                return ResponseTemplate.builder().code(1).message("删除失败").count(0l).build();
            }
        } catch (Exception e) {
            //遇到异常，返回异常原因
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResponseTemplate.builder().code(1).message(e.getMessage()).count(0l).build();
        }finally {
            lock.unlock();
        }
    }
    /**
     *@Description:通过pks批量逻辑删除记录
     *@Param: [listPks]
     *@return: com.koocloud.electroplatemanage.common.ResponseTemplate
     *@Author: wjx
     *@date: 2020/11/16
     */
    @Override
    public ResponseTemplate batchDeleteByPks(List<String> listPks) {
        if(!listPks.isEmpty()) {
            try {
                lock.lock();
                //存在合法pk值，进行批量删除操作
                int rows = tankMapper.batchDeleteByPks(listPks);
                //判断批量删除操作是否成功
                if (rows > 0) {
                    //批量删除成功返回数据
                    return ResponseTemplate.builder().code(0).message("批量删除成功").count((long)rows).build();
                } else {
                    //批量删除失败返回提示
                    return ResponseTemplate.builder().code(1).message("批量删除失败").count(0l).build();
                }
            } catch (Exception e) {
                //遇到异常，返回异常原因
                e.printStackTrace();
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return ResponseTemplate.builder().code(1).message(e.getMessage()).count(0l).build();
            }finally {
                lock.unlock();
            }
        }
        else {
            return ResponseTemplate.builder().code(1).message("传入参数为空").count(0l).build();
        }
    }
    /**
     *@Description:修改一条记录
     *@Param: [typeWorkVo]
     *@return: com.koocloud.electroplatemanage.common.ResponseTemplate
     *@Author: wjx
     *@date: 2020/11/16
     */
    @Override
    public ResponseTemplate update(Tank tank) {
        try {
            lock.lock();
            String tankNo = tank.getTankNo();
            List<OriginItems> originItemsList = tank.getOriginItemsList();
            //没有异常并且修改数据条数大于0
            int rows = tankMapper.update(tank);
            originItemsMapper.deleteByTankNo(tankNo);
            originItemsMapper.batchInsert(tankNo,originItemsList);
            if(rows>0) {
                return ResponseTemplate.builder().code(0).message("修改数据成功").count(1l).build();
            }
            else {//没有异常并且修改数据失败，原则上不出现
                return ResponseTemplate.builder().code(1).message("修改数据失败").count(0l).build();
            }
        } catch (Exception e) {
            //出现异常返回异常原因
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResponseTemplate.builder().code(1).message(e.getMessage()).count(0l).build();
        }finally {
            lock.unlock();
        }
    }

    public void  log(String str){
        System.out.println("====================>"+str+"=================>");
    }
}
